package com.janson.ShiroConfig;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author Janson
 * @Date 2022/4/5 16:22
 * @Version 1.0
 */
@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean  第三步
    @Bean
    public ShiroFilterFactoryBean getshirofilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro 的内置过滤器
        /**
         *  anon : 无需认证就可以访问
         *  authc ： 必须认证才能访问
         *  user ： 必须拥有 记住我 功能才能用
         *  perms ： 拥有对某个资源的权限才能访问
         *  role： 拥有某个角色权限才能访问
         */
        Map<String,String> filterMap = new LinkedHashMap();
        //filterMap.put("/user/add","authc");
        //filterMap.put("/user/update","authc");
        //采用通配符也可以

        //授权，正常情况下，，没有授权，就会跳转到未授权页面
        filterMap.put("/user/update","perms[user:update]");

        filterMap.put("/user/*","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //未授权 跳转的页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noauth");
        return shiroFilterFactoryBean;
    }

    //DafaulWebSecurityManager  第二步
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("shiroRealm") ShiroRealm shiroRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联 ShiroRealm
         securityManager.setRealm(shiroRealm);
        return securityManager;
    }

    // 创建 realm 对象  1.第一步
    @Bean
    public ShiroRealm shiroRealm(){

        return new ShiroRealm();
    }
    @Bean
    public ShiroDialect getshiroDialect(){
        return new ShiroDialect();
    }

}
